<template>
    <a-layout>
        <a-layout-sider width="200" style="background: #fff">
            <a-menu
                    v-model:selectedKeys="selectedKeys2"
                    v-model:openKeys="openKeys"
                    mode="inline"
                    :style="{ height: '100%', borderRight: 0 }"
            >
                <a-sub-menu key="sub1">
                    <template #title>
              <span>
                <user-outlined />
                商家管理
              </span>
                    </template>
                    <a-menu-item key="1">option1</a-menu-item>
                    <a-menu-item key="2">option2</a-menu-item>
                    <a-menu-item key="3">option3</a-menu-item>
                    <a-menu-item key="4">option4</a-menu-item>
                </a-sub-menu>
                <a-sub-menu key="sub2">
                    <template #title>
              <span>
                <laptop-outlined />
                商品管理
              </span>
                    </template>
                    <a-menu-item key="/admin/manager">
                        <router-link to="/admin/manager">品牌管理</router-link>
                    </a-menu-item>
                    <a-menu-item key="/admin/specification">
                        <router-link to="/admin/specification">规格管理</router-link>
                    </a-menu-item>
                    <a-menu-item key="/admin/typetemlate">
                        <router-link to="/admin/typetemlate">模板管理</router-link>
                    </a-menu-item>
                    <a-menu-item key="/admin/item">
                        <router-link to="/admin/item">分类管理</router-link>
                    </a-menu-item>
                    <a-menu-item key="9">
                        商品审核
                    </a-menu-item>
                </a-sub-menu>
                <a-sub-menu key="sub3">
                    <template #title>
              <span>
                <notification-outlined />
                广告管理
              </span>
                    </template>
                    <a-menu-item key="/admin/contentcate">
                        <router-link to="/admin/contentcate">广告类别</router-link>
                    </a-menu-item>
                    <a-menu-item key="/admin/content">
                        <router-link to="/admin/content">广告内容</router-link>
                    </a-menu-item>
                </a-sub-menu>
            </a-menu>
        </a-layout-sider>
        <a-layout style="padding: 0 24px 24px">
            <a-layout-content
                    :style="{ background: '#ffffff', padding: '24px', margin: 0, minHeight: '280px' }"
            >
                <p>
                    <a-button type="primary" @click="add">新建</a-button>
                </p>

                <a-table :dataSource="templates"
                         :columns="columns"
                         :row-key="record=>record.id"
                         :pagination="pagination"
                         :loading="loading"
                         @change="handleTableChange">
                    <template #brandIds='{text,record,index}'>
                        {{jsonToString(text,'text')}}
                    </template>
                    <template #specIds='{text,record,index}'>
                        {{jsonToString(text,'text')}}
                    </template>
                    <template #customAttributeItems='{text,record,index}'>
                        {{jsonToString(text,'text')}}
                    </template>
                    <template v-slot:action="{text,record}">
                        <a-button type="primary"  @click="edit(record)">
                            编辑
                        </a-button>
                        <a-popconfirm
                                title="删除后无法恢复，确认删除?"
                                ok-text="是"
                                cancel-text="否"
                                @confirm="del(record.id)"
                        >
                            <a-button type="danger">
                                删除
                            </a-button>
                        </a-popconfirm>
                    </template>
                </a-table>
            </a-layout-content>
        </a-layout>
        <a-modal
                v-model:visible="modalVisible"
                title="商品模板编辑表单"
                :confirm-loading="modalLoading"
                @ok="handlModalOk"
                cancel-text="取消"
                ok-text="确定">

            <a-form :model="templateEntity" :label-col="{span:6}" :wrapper-col="wrapperCol">
                <a-form-item label="分类模板名称">
                    <a-input v-model:value="templateEntity.name" />
                </a-form-item>

                <a-form-item label="关联品牌">
                    <a-select
                            v-model:value="templateEntity.brandIds"
                            mode="multiple"
                            style="width: 100%"
                            placeholder="选择品牌..."
                            :labelInValue="true"
                    >
                        <a-select-option v-for="item in brandList"
                                         :key="item.id"
                                         :value="item.id"
                                         :label="item.name"
                        >
                            {{item.name}}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="关联规格">
                    <a-select
                            v-model:value="templateEntity.specIds"
                            mode="multiple"
                            style="width: 100%"
                            placeholder="选择规格..."
                            :labelInValue="true"
                    >
                        <a-select-option v-for="item in specificationList"
                                         :key="item.id"
                                         :value="item.id"
                                         :label="item.specName"
                        >
                            {{item.specName}}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="扩展属性">
                    <a-button type="primary" :size="small" @click="addTableRow">新增扩展属性</a-button>
                    <table id="tb01" width="340px" >
                        <thead>
                        <tr>
                            <td>属性名称</td>
                            <td>操作</td>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="pojo in templateEntity.customAttributeItems" v-bind:key="pojo.id">
                            <td><a-input v-model:value="pojo.text"/></td>
                            <td><a-button :size="small" danger block @click="deleTableRow($index)">删除</a-button></td>
                        </tr>
                        </tbody>
                    </table>
                </a-form-item>
            </a-form>
        </a-modal>
    </a-layout>
</template>


<script lang="ts">
    import {onMounted, ref} from "vue";
    import axios from "axios";
    import {message} from "ant-design-vue";

    export default {
        name: "Typetemplate",
        setup(){
            const templates =ref();
            const templateEntity =ref<any>({
                customAttributeItems:[]
            });
            const pagination=ref({
                current:1,
                pageSize:4,
                total:0,
            });
            const loading = ref(false);
            const modalVisible = ref<boolean>(false);
            const modalLoading = ref<boolean>(false);
            const maxTagTextLength=ref(10);
            const brandOptions =ref([]);
            const brandList=ref();
            const specifications = ref();
            const specificationList = ref();
            const columns= [
                {
                    title: '模板id',
                    dataIndex: 'id',
                },
                {
                    title: '分类模板名称',
                    dataIndex: 'name',
                },
                {
                    title: '关联品牌',
                    dataIndex: 'brandIds',
                    slots: {customRender:'brandIds'}
                },
                {
                    title: '关联规格',
                    dataIndex: 'specIds',
                    slots: {customRender:'specIds'}
                },
                {
                    title: '扩展属性',
                    dataIndex: 'customAttributeItems',
                    slots: {customRender:'customAttributeItems'}
                },
                {
                    title: 'Action',
                    key: 'action',
                    slots: {customRender:'action'}
                },

            ];
            //数据查询
            const handleQuery=(params:any)=>{
                loading.value=true;
                axios.get('http://localhost:8899/brand-query/typeTemplate-Ms/listByPage',{
                    params:{
                        page:params.page,
                        size:params.size,
                    }
                }).then((response)=>{
                    loading.value=false;
                    templates.value=response.data.list;
                    //重置分页按钮
                    pagination.value.current=params.page;
                    pagination.value.total=response.data.total;
                });
            };
            //点中分页导航
            const handleTableChange=(pagination:any)=>{
                handleQuery({
                    page:pagination.current,
                    size:pagination.size
                })
            };
            //添加
            const add=()=>{
                modalVisible.value=true;
                templateEntity.value={
                    customAttributeItems: []
                };
            };
            //删除
            const del=(id:number)=>{
                axios.delete('http://localhost:8899/brand-query/typeTemplate-Ms/delete/'+id).then(response=>{
                    if(response.data.code==200){
                        //加载最新数据
                        handleQuery({
                            page:pagination.value.current,
                            size:pagination.value.pageSize
                        });
                    }else {
                        message.error(response.data.message);
                    }
                })
            }
            //修改
            const edit=(record:any)=>{

                modalVisible.value=true;
                let id = record.id;
                axios.get('http://localhost:8899/brand-query/typeTemplate-Ms/findOne?id='+id).then((response)=>{

                    modalVisible.value=true;
                    templateEntity.value=response.data; //json格式
                    templateEntity.value.brandIds = JSON.parse(templateEntity.value.brandIds);
                    templateEntity.value.specIds = JSON.parse(templateEntity.value.specIds);
                    //templateEntity.value.name = JSON.parse(templateEntity.value.name);
                    //templateEntity.value.specName = JSON.parse(templateEntity.value.specName);
                    // console.log(templateEntity.value);
                    // console.log(templateEntity.value.name);
                    // console.log(templateEntity.value.brandIds);
                })

            };
            //添加
            const handlModalOk=()=>{
                modalLoading.value = false;

                let template_arr:Array<any> = [];
                (templateEntity.value.brandIds as Array<any>).forEach(item=>{
                    template_arr.push({
                        id:item.option.value,
                        text:item.option.label
                    })
                });
                //转json对象（集合）为字符串
                templateEntity.value.brandIds =  JSON.stringify(template_arr);

                let spec_arr:Array<any> = [];
                (templateEntity.value.specIds as Array<any>).forEach(item=>{
                    spec_arr.push({
                        id:item.option.value,
                        text:item.option.label
                    })
                });
                //转json对象（集合）为字符串
                templateEntity.value.specIds = JSON.stringify(spec_arr);

                templateEntity.value.customAttributeItems = JSON.stringify(templateEntity.value.customAttributeItems);

                axios.post('http://localhost:8899/brand-query/typeTemplate-Ms/update',templateEntity.value).then((respone)=>{
                    modalLoading.value = false;
                    if (respone.data.success==true){
                        modalVisible.value = false;
                        handleQuery({
                            page:pagination.value.current,
                            size:pagination.value.pageSize
                        });
                    } else {
                        message.error(respone.data.message);
                    }
                });
            };
            const jsonToString = (jsonString:any,key:any)=>{
                let json= JSON.parse(jsonString);
                let value="";
                for(let i=0;i<json.length;i++){
                    if(i>0){
                        value+=",";
                    }
                    value +=json[i][key];
                }
                return value;
            };
            //加载品牌列表
            const handleBrandIds=()=> {
                modalVisible.value = true;
                axios.get('http://localhost:8899/brand-query/querybrand').then(response => {
                   brandList.value = response.data;
                   console.log(brandList.value);
                })
            };
            //加载规格列表
            const handleSpecIds = ()=>{
                axios.get('http://localhost:8899/brand-query/specification-Ms/findAll').then((response)=>{
                    specificationList.value = response.data;
                    //console.log(specificationList.value);
                });
            }
            //添加新行
            const addTableRow = ()=>{
                templateEntity.value.customAttributeItems.push({});
            };

            //删除行
            const deleTableRow = (index:number) =>{
                templateEntity.value.customAttributeItems.splice(index,1);
            };
            onMounted(()=>{
                handleQuery({
                    page:1,
                    size:pagination.value.pageSize,
                });
                //handleLoadNewsCategory();
                handleSpecIds();
                handleBrandIds();
            });
            return{
                templates,
                templateEntity,
                pagination,
                loading,
                modalVisible,
                modalLoading,
                maxTagTextLength,
                brandOptions,
                brandList,
                specifications,
                specificationList,
                columns,
                handleQuery,
                handleTableChange,
                add,
                edit,
                del,
                handlModalOk,
                jsonToString,
                handleBrandIds,
                deleTableRow,
                addTableRow,
                handleSpecIds,
            }

        }

    }
</script>